package com.linkage.jz.bankruptcy.activity.Project;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ProPublic;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Project.ProFlowFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialogTep;
import com.linkage.seapeak.activity.vote.CreditorMultiSelectActivity;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 创建任务
 */
public class CreateProPublicActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = CreateProPublicActivity.class.getSimpleName();
    public static final String KEY_ACTION = "action";
    public static final String KEY_PUBLIC = "public";

    public final int REQUEST_CODE_MEMBER = 10001;
    public final int REQUEST_CODE_SELFLOW = 10002;


    private String mProjectId;
    private ProPublic mProPublic;
    private String mMembers = "";
    private String mFlowId = "";

    private RecyclerView mImgRecyclerView;
    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;

    private EditText et_public_name, et_public_desc;
    private TextView tv_public_type, tv_public_member, tv_public_flow;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {

    }

    @Override
    public void initView() {

    }

    private CommonPromptDialog mPromptDialog;
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CreateProPublicActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_pro_public);
        super.onCreate(savedInstanceState);

        titlebar_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (TextUtils.equals(getIntent().getStringExtra(KEY_ACTION), "edit")) {
            mProPublic = (ProPublic) getIntent().getSerializableExtra(KEY_PUBLIC);
            mProjectId = mProPublic.getBankruptcyProjectId();
        } else {
            mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        }
        if (mProPublic != null) {
            titlebar_title.setText("编辑公示");
        } else {
            titlebar_title.setText("新增公示");
        }
        initViews();
        titlebar_menu_text.setOnClickListener(this);
        tv_public_flow.setOnClickListener(this);
    }

    public void initViews() {
        titlebar_menu_text.setVisibility(View.VISIBLE);
        et_public_name = findViewById(R.id.et_public_name);
        et_public_desc = findViewById(R.id.et_public_desc);
        tv_public_type = findViewById(R.id.tv_public_type);
        tv_public_member = findViewById(R.id.tv_public_member);
        tv_public_flow = findViewById(R.id.tv_public_flow);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
        mImgRecyclerView.setLayoutManager(mImgAdapter.createLayoutManager());
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);

        if (mProPublic != null) {
            et_public_name.setText(mProPublic.getPublicName());
            et_public_desc.setText(mProPublic.getPublicDetail());
            tv_public_type.setText(mProPublic.getPublicType());
            if (mProPublic.getProjectSchedule() != null) {
                tv_public_flow.setText(mProPublic.getProjectSchedule().getNodeName());
                mFlowId = mProPublic.getProjectSchedule().getId();
            }
            if (mProPublic.getMemberList() != null && mProPublic.getMemberList().size() > 0) {
                String ids = "";
                String names = "";
                for (int i = 0; i < mProPublic.getMemberList().size(); i++) {
                    ids = ids + mProPublic.getMemberList().get(i).getCreditorId() + ",";
                    names = names + mProPublic.getMemberList().get(i).getCreditorName() + ",";
                }
                mMembers = ids;
                tv_public_member.setText(names);
            }

//            mFlowId = mProPublic.getProjectSchedule().getId();

            for (int i = 0; i < mProPublic.getAttachmentList().size(); i++) {
                TaskAtta atta = mProPublic.getAttachmentList().get(i);
                JSONObject obj = new JSONObject();
                try {
                    obj.putOpt("filename", atta.getAttachmentName());
                    obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                    obj.putOpt("filesize", atta.getAttachmentSize());
                    obj.putOpt("loadUrl", atta.getAttachmentWatermarkAddress());
                    mImgList.add(new Gson().fromJson(obj.toString(), UploadImage.class));

                    BaseCreateActivity.sorFiles(mImgList, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_MEMBER:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        mMembers = data.getStringExtra("seluserId");
                        tv_public_member.setText(data.getStringExtra("seluserName"));
                    }
                }
                break;
            case REQUEST_CODE_SELFLOW:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        mFlowId = data.getStringExtra(ProFlowFragment.KEY_FLOW_ID);
                        tv_public_flow.setText(data.getStringExtra(ProFlowFragment.KEY_FLOW_NAME));
                    }
                }
            default:

                break;
        }
    }

    private CommonPromptDialogTep mTypeDialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_public_type:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请选择公示类型");
                final String[] strTypes = getResources().getStringArray(R.array.type_project_public);
                builder.setItems(R.array.type_project_public, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tv_public_type.setText(strTypes[which]);
                    }
                });
                builder.show();
                break;

            case R.id.tv_public_type_add:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                mTypeDialog = new CommonPromptDialogTep(this, CommonPromptDialog.TYPE_EDIT_SINGLE);
                mTypeDialog.setTitle("添加分类");
                mTypeDialog.setEditHint("请输入分类");
                mTypeDialog.setPositiveClickListener("取消", new OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        mTypeDialog.dismiss();
                    }
                });
                mTypeDialog.setNegativeClickListener("确定", new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String type = mTypeDialog.dialog_prompt_edit_single.getText().toString().trim();
                        if (TextUtils.isEmpty(type)) {
                            ToastUtil.showShort("请填写分类");
                        } else {
                            tv_public_type.setText(type);
                            mTypeDialog.dismiss();
                        }
                    }
                });
                mTypeDialog.show();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.titlebar_menu_text:
                saveData();
                break;
            case R.id.tv_public_member:
                Intent intent = new Intent(this, CreditorMultiSelectActivity.class);
                intent.putExtra("projectId", mProjectId);
                intent.putExtra("type", "1");
                intent.putExtra("seltype", "1");
                startActivityForResult(intent, REQUEST_CODE_MEMBER);
                break;
            case R.id.tv_public_flow:
                Intent intent1 = new Intent(this, SelProFlowListActivity.class);
                intent1.putExtra(KEY_PROJECTID, mProjectId);
                startActivityForResult(intent1, REQUEST_CODE_SELFLOW);
                break;

            default:
                break;
        }


    }


    public void saveData() {
        String name = et_public_name.getText().toString();
        String desc = et_public_desc.getText().toString();
        String type = tv_public_type.getText().toString();


        if (TextUtils.isEmpty(name)) {
//            ToastUtil.showShort("名称不能为空");
            showToast("公示事项不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        int countnum = 0;
        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            countnum++;
        }

        if (countnum == 0) {
//            ToastUtil.showShort("请上传公示资料");
            showToast("请上传公示资料", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(type)) {
//            ToastUtil.showShort("请选择公示类型");
            showToast("请选择公示类型", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }



//        if (TextUtils.isEmpty(mFlowId)) {
////            ToastUtil.showShort("请选择进度节点");
//            showToast("请选择进度节点", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//            return;
//        }
//        if (TextUtils.isEmpty(mMembers)) {
////            ToastUtil.showShort("请选择公示对象");
//            showToast("请选择公示对象", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//            return;
//        }

        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }
        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();

        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(mImgList.get(i).getFilename())) {
                    obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("attachmentName", mImgList.get(i).getFilename());
                }
                obj.putOpt("attachmentDownloadAddress", mImgList.get(i).getFilepath());
                obj.putOpt("attachmentSize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        JSONArray memberArr = new JSONArray();
        String members = "";
        if("".equalsIgnoreCase(mMembers))
        {
            members = mMembers;
        }else {
            String[] marr = mMembers.split(",");
            for (String s : marr) {
                JSONObject obj = new JSONObject();
                try {
                    obj.putOpt("creditorId", s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                memberArr.put(obj);
            }
            members = memberArr.toString();
        }





        Observable<JsonObject> observable;
        if (mProPublic != null) {
            observable = Network
                    .getAPIService()
                    .editPublic(getUserToken(), mProPublic.getId(), mProPublic.getBankruptcyProjectId(),
                            name, desc, mFlowId, type,members , fileArr.toString());
        } else {
            observable = Network
                    .getAPIService()
                    .createPublic(getUserToken(), mProjectId, name, desc, mFlowId, type,
                            members, fileArr.toString());
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_PUBLIC);
                        EventBus.getDefault().post(event);
//                        ToastUtil.showShort("提交成功");
                        showToast("提交成功", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.SUCCESS);
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }
}

